package com.ruoyi.netty.handler;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.netty.Command;
import com.ruoyi.netty.MessageType;
import com.ruoyi.netty.NettyServer;
import com.ruoyi.netty.Result;
import com.ruoyi.netty.command.ChatMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

import java.util.Objects;

/**
 * @author Zoo
 */
public class ChatHandler {

    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame){
        try{
            ChatMessage chat = JSON.parseObject(frame.text(), ChatMessage.class);
            switch (MessageType.match(chat.getType())){
                case PRIVATE:
                    if (StringUtil.isNullOrEmpty(chat.getTarget())){
                        ctx.channel().writeAndFlush(Result.fail("消息发送失败，请指定发送对象"));
                        return;
                    }
                    Channel channel = NettyServer.USERS.get(chat.getTarget());
                    if (null == channel || !channel.isActive()){
                        ctx.channel().writeAndFlush(Result.fail("消息发送失败，对方不在线"));
                    }else {
                        ctx.channel().writeAndFlush(Result.success("私聊消息（"+chat.getNickname()+"）"+chat.getContent()));
                        channel.writeAndFlush(Result.success("私聊消息（"+chat.getNickname()+"）"+chat.getContent()));
                    }
                    break;
                case GROUP:
                    NettyServer.GROUP.writeAndFlush(Result.success("群聊天消息"+chat.getContent()));
                    break;
                default:
                    ctx.channel().writeAndFlush(Result.fail("不支持的消息类型"));
                    break;
            }
        }catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail("发送消息格式有误"));
        }
    }
}
